package com.lg.meng.widgets;

import android.content.Context;
import android.content.res.TypedArray;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.widget.FrameLayout;

import com.lg.meng.R;


/**
 * createBy: Ligang
 * date: 2018/9/7
 * description: 基于宽来设置高或基于高设置宽
 * 使用方法：
 * android:layout_width="match_parent"
 * android:layout_height="wrap_content"
 * app:height_percent="56.85%w"
 */
public class PercentFrameLayout extends FrameLayout {
    private String heightPercent;
    private String widthPercent;

    public PercentFrameLayout(@NonNull Context context) {
        super(context);
        init(context, null);
    }

    public PercentFrameLayout(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    public PercentFrameLayout(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    /**
     * 初始化自定义属性
     *
     * @param context
     * @param attrs
     */
    private void init(Context context, AttributeSet attrs) {
        if (attrs != null) {
            TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.PercentView);
            heightPercent = typedArray.getString(R.styleable.PercentView_height_percent);
            widthPercent = typedArray.getString(R.styleable.PercentView_width_percent);
            typedArray.recycle();
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        if (!TextUtils.isEmpty(heightPercent)) {
            String[] split = heightPercent.split("%");
            float value = Float.parseFloat(split[0]);
            if ("w".equalsIgnoreCase(split[1])) {
                int wsize = MeasureSpec.getSize(widthMeasureSpec);
                int height = (int) (wsize * value / 100);
                setMeasuredDimension(wsize, height);
                super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY));
                return;
            }
        } else if (!TextUtils.isEmpty(widthPercent)) {
            String[] split = widthPercent.split("%");
            float value = Float.parseFloat(split[0]);
            if ("h".equalsIgnoreCase(split[1])) {
                int hsize = MeasureSpec.getSize(heightMeasureSpec);
                int width = (int) (hsize * value / 100);
                setMeasuredDimension(width, hsize);
                super.onMeasure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), heightMeasureSpec);
                return;
            }
        }
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }
}
